#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
'''自定义认证功能'''
import importlib
from django.contrib.auth import hashers
from django.conf import settings


hasher = getattr(hashers,settings.AUTH_HASHER)    # 获取Hash算法

app_name,model_name = settings.AUTH_USER_MODEL.split('.')
models = importlib.import_module(app_name+'.models')
auth_model = getattr(models,model_name)    # 获取认证使用的model


def check_password(username,password):
    '''验证用户名和密码,以及是否处于激活状态'''
    username_key = {auth_model.USERNAME_FIELD: username}
    user_obj = auth_model.objects.filter(**username_key).first()
    if user_obj:
        user_password = getattr(user_obj,auth_model.PASSWORD_FIELD)
        salt = user_obj.password.split('$')[2]
        if hasher.encode(hasher,password,salt) == user_password:
            if user_obj.is_active:
                return user_obj
    return None
